package data

import (
	"github.com/go-kratos/kratos/v2/config"
	"github.com/go-kratos/kratos/v2/config/file"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/wire"
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	logger2 "gorm.io/gorm/logger"
	log2 "log"
	"mykratos/internal/conf"
	"os"
	"time"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewCartRepository)

// Data .
type Data struct {
	// TODO wrapped database client
	db *gorm.DB
}

// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
	//读取配置
	conf := config.New(
		config.WithSource(
			file.NewSource("../../configs/config.yaml"),
		),
		config.WithDecoder(func(kv *config.KeyValue, v map[string]interface{}) error {
			// kv.Key
			// kv.Value
			// kv.Format
			// 自定义实现对应的数据源解析，如果是配置中心数据源也可以指定对应的 format 进行识别配置类型
			return yaml.Unmarshal(kv.Value, v)
		}),
	)
	// 加载配置源：
	if err := conf.Load(); err != nil {
		log2.Fatal(err)
	}

	//gorm的日志
	newLogger := logger2.New(
		log2.New(os.Stdout, "\r\n", log2.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger2.Config{
			SlowThreshold:             time.Second,    // 慢 SQL 阈值
			LogLevel:                  logger2.Silent, // 日志级别
			IgnoreRecordNotFoundError: true,           // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,          // 禁用彩色打印
		},
	)
	// 获取对应的值内容：
	b, err := conf.Value("data.database.source").String()
	if err != nil {
		log2.Fatal("data.database.source Load Failed")
	}
	dsn := b + "?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})

	if err != nil {
		return nil, nil, err
	}
	d := &Data{
		db: db,
	}
	logHelp := log.NewHelper(logger)
	return d, func() {
		logHelp.Info("message", "closing the data resources")
	}, nil
}
